<?php

namespace App\Console\Commands\Activity\Nsq;

use App\Enums\Common\NsqEnum;
use App\Service\Activity\ShopActivityService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class OrderPaySyncActivityJoinAddressCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'activity:nsq-sub:kfos.order.deliveryNote.created';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'activity:nsq - 订货订单同步订单地址数据信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws Exception
     */
    public function handle(): int
    {
        ini_set('memory_limit', '4G');
        (new NsqSubscriber(config('nsq.default.address')))->sub(
            NsqEnum::TOPIC_KFOS_MERCHANT_ORDER_ADDRESS_CREATED,
            NsqEnum::CHANNEL_TIGER_MERCHANT_ORDER_ADDRESS_CREATED_EVENT,
            function (Message $message) {
                Log::info($this->description, $message->data());

                try {
                    // 统一业务处理
                    $this->doHandle($message->data());
                } catch (Exception $exception) {
                    logException($this->description, $exception, $message->data(), true, true);
                } finally {
                    $message->done();
                }
            }
        );
        return 0;
    }


    /**
     * 业务统一处理
     *
     * @param array $data
     * @throws Exception
     */
    private function doHandle(array $data)
    {
        list($orderId, $uuid) = [
            attributeGet($data, "id", 0), // 订单id
            attributeGet($data, "new_order_uuid", ""),// uuid 关联活动参与
        ];

        if (!$orderId) {
            return;
        }

        // 消杀活动 订单地址创建完成-更新记录
        if ($uuid) {
            ShopActivityService::syncActivityJoinAddressDetail($data);
        }

    }
}
